import { relationalStore, ValuesBucket } from "@kit.ArkData";
import { FnContext, LogTag, Option, _appInfo, _appInfo2 } from "CoffeeSdk";


const FileName = "SqlUtil";

export type SqlDataType = string | number | boolean | Uint8Array;

export type KeyValuePairs = Map<string, SqlDataType>

/**
 *
 * @param pairs
 * @param ignoreUndefined
 * undefined的不写入,直接过滤.
 * 应该如果要置空,应该传null.
 * @returns
 */
export function getPairsKeyValues(pairs: KeyValuePairs): [string[], SqlDataType[]] {
  const keys: string[] = [];
  const values: SqlDataType[] = [];
  for (const [key, value] of pairs.entries()) {
    if (value === undefined) {
      continue;
    }
    keys.push(key);
    values.push(value);
  }
  return [keys, values];
}

export function getBucketKeyValues(bucket: ValuesBucket): [string[], SqlDataType[]] {
  const _keys: string[] = Object.keys(bucket);
  const values: SqlDataType[] = [];
  const keys: string [] = [];
  for (const key of _keys) {
    const value = bucket[key];
    if (value === undefined) {
      continue;
    }
    keys.push(key);
    values.push(value);
  }
  return [keys, values];
}


/**
 * WHERE语句中,一个查询条件单位
 */
export interface ConditionUnit {
  sql: string // 一个基本条件 eg: folder_id = ?
  values: SqlDataType[] //具体的参数值数组,一个条件里可能有多个参数.
}

/**
 * 返回 sql的WherePart 以及 参数数组
 * 如果没有条件,WherePart是空字符串.
 * @param units
 * @returns
 * 没有条件,返回空字符串,
 * 有条件,返回 `WHERE key1 = ? AND key2 = ?`
 */
export function getWherePartFromConditionUnits(units: Option<ConditionUnit[]>): [string, SqlDataType[]] {
  const args: SqlDataType[] = [];
  if (!units || !units.length) {
    return ["", []];
  }
  const sqlUnits: string[] = [];
  for (const unit of units) {
    sqlUnits.push(unit.sql);
    args.push(...unit.values);
  }
  const sqlUnitsString = sqlUnits.join(" AND ");
  const wherePart = `WHERE ${sqlUnitsString}`;
  return [wherePart, args];
}

/**
 *
 * @param sql SELECT * FROM xxx;
 * @param units
 * @returns
 */
export function addWherePartWithConditionUnits(sql: string, units: ConditionUnit[]): [string, SqlDataType[]] {
  const [wherePart, args] = getWherePartFromConditionUnits(units);
  let newSql = sql;
  if (wherePart) {
    newSql = `${sql} ${wherePart}`;
  }
  return [newSql, args];
}

export function getTimeDif(startTime: Date): number {
  const start = startTime.getTime();
  const now = Date.now();
  return now - start;
}

/**
 * 遍历ResultSet的每一行
 * @param resultSet
 * @param fn
 */
export function resultSetRowForEach(resultSet: relationalStore.ResultSet, fn: (rowIndex: number) => void) {
  if (resultSet.goToFirstRow()) {
    let rowIndex = 0;
    fn(rowIndex);
    while (resultSet.goToNextRow()) {
      rowIndex++;
      fn(rowIndex);
    }
  }
}
